﻿using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace NCommonLib.Extensions
{
    public static class ThreadExtensions
    {
        public static async Task<T> WithCancellation<T>(this Task<T> task, CancellationToken cancellationToken)
        {
            var tcs = new TaskCompletionSource<bool>();
            using (cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).TrySetResult(true), tcs))
            {
                if (task != await Task.WhenAny(task, tcs.Task))
                {
                    //Debug.WriteLine("Cancelling------>");
                    return default(T);
                }
            }
            return await task;
        }

        public static Task<T> WithNCancellation<T>(this Task<T> task, CancellationToken cancellationToken)
        {
            TaskCompletionSource<T> taskCompletionSource = new TaskCompletionSource<T>();
            CancellationTokenRegistration  registration = cancellationToken.Register(() =>
            {
                taskCompletionSource.TrySetCanceled();
            });

            task.ContinueWith(t =>
                {
                    registration.Dispose();
                    if (t.IsCanceled)
                    {
                        taskCompletionSource.TrySetCanceled();
                    }
                    else if (t.IsFaulted)
                    {
                        taskCompletionSource.TrySetException(t.Exception.InnerException);
                    }
                    else
                    {
                        taskCompletionSource.TrySetResult(t.Result);
                    }
                });
            return taskCompletionSource.Task;
        }
    }
}
